//
//  CBPeripheralManagerDelegate.swift
//  DashBoard
//
//  Created by 王麒皓 on 2023/7/15.
//

import Foundation
import CoreBluetooth
import os
import SwiftUI

class MyCBPeripheralManagerDelegate: NSObject, CBPeripheralManagerDelegate {
    var peripheralManager: CBPeripheralManager?
    @Environment(\.scenePhase) var scene
    
    override init() {
        super.init()
        
        self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: [CBPeripheralManagerOptionShowPowerAlertKey: true])
    }
    
    func setupPeripheral() {
        if BLEName != "" {
            
            //MARK: BLE
            
            // Build our service.
            
            // Start with the CBMutableCharacteristic.
            print(BLEName)
            let transferCharacteristic = CBMutableCharacteristic(type: CBUUID(string: BLEName),
                                                                 properties: [.notify, .writeWithoutResponse],
                                                                 value: nil,
                                                                 permissions: [.readable, .writeable])
            
            // Create a service from the characteristic.
            let transferService = CBMutableService(type: CBUUID(string: BLEName), primary: true)
            
            // Add the characteristic to the service.
            transferService.characteristics = [transferCharacteristic]
            
            // And add it to the peripheral manager.
            peripheralManager?.add(transferService)
            peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [CBUUID(string: BLEName)]])
        }
    }
    
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if scene == .background {
            print("Stop advertising...")
            peripheralManager?.removeAllServices()
            peripheralManager?.stopAdvertising()
        }
        switch peripheral.state {
        case .poweredOn:
            // ... so start working with the peripheral
            os_log("CBManager is powered on")
            setupPeripheral()
        case .poweredOff:
            os_log("CBManager is not powered on")
            // In a real app, you'd deal with all the states accordingly
            return
        case .resetting:
            os_log("CBManager is resetting")
            // In a real app, you'd deal with all the states accordingly
            return
        case .unauthorized:
            // In a real app, you'd deal with all the states accordingly
            os_log("You are not authorized to use Bluetooth")
            return
        case .unknown:
            os_log("CBManager state is unknown")
            // In a real app, you'd deal with all the states accordingly
            return
        case .unsupported:
            os_log("Bluetooth is not supported on this device")
            // In a real app, you'd deal with all the states accordingly
            return
        @unknown default:
            os_log("A previously unknown peripheral manager state occurred")
            // In a real app, you'd deal with yet unknown cases that might occur in the future
            return
        }
    }
    
    
}
